<?php
if(!defined ("BASEPATH"))exit("No direct script allowed");

	class zulModel extends CI_Model{
		
		public $table_name		= "";
		public $primary_key		= "";
		public $primaryFilter	= "intval";
		public $order_by		= "";
		
		function __construct(){
			parent::__construct();
		}
		function get($ids = FALSE,$single = TRUE){
			if ($ids != FALSE) {
				is_array($ids) || $ids = array($ids); 
				
				$filter = $this->primaryFilter;
				$ids = array_map($filter, $ids); 
				
				$this->db->where_in($this->primary_key, $ids);
			}
			
			count($this->db->ar_orderby) || $this->db->order_by($this->order_by);
			
			$single == FALSE || $this->db->limit(10);
			$method = $single ? 'row_array' : 'result_array';
			return $this->db->get($this->table_name)->$method();
		}
		function get_by($key, $val = FALSE, $orwhere = FALSE, $single = FALSE){
			if(!is_array($key)){
				$this->db->where(htmlentities($key),htmlentities($val));
			}else{
				$key			= array_map('htmlentities',$key);
				$where_method	= $orwhere	== TRUE ? "or_where" : "where";
				$this->db->$where_method($key);
			}
			
			$single == FALSE || $this->db->limit(1);
			$method = $single ? 'row_array' : 'result_array';
			return $this->db->get($this->table_name)->$method();
		}
		function get_key_value($key_field, $value_field, $ids = FALSE){
			$this->db->select($key_field . ", " . $value_field);
			$result	= $this->get($ids);
			
			$data	= array();
			if(count($result) > 0){
				if($ids != FALSE && !is_array($ids)){
					$result	= array($result);
				}
				foreach($result as $row){
					$data[$row[$key_field]]	= $row[$value_field];
				}
			}
			return $data;
		}
		function get_join($data,$ids,$single=FALSE){
			foreach($data as $row){
				$this->db->join($row["join_table"],$row["table"].".".$row["join_key"]."=".$row["join_table"].".".$row["join_key"]);
			}
			$this->db->where_in($this->primary_key, $ids);
			count($this->db->ar_orderby) || $this->db->order_by($this->order_by);
			$this->db->select("*")->from($this->table_name);
			$single == FALSE || $this->db->limit(1);
			$method = $single ? 'row_array' : 'result_array';
			return $this->db->get()->$method();
		}
		public function save($data, $id = FALSE){
			if($id == FALSE){
				// it sholud be an insert :)
				$this->db->set($data)->insert($this->table_name);
			}else{
				// it sholud be an update :)
				$filter	= $this->primaryFilter;
				$this->db->set($data)->where($this->primary_key, $filter($id))->update($this->table_name);
			}
			return	$id	== FALSE ? $this->db->insert_id() : $id;
		}
		public function delete($ids){
			if($ids){
				$ids	= explode(",",$ids);
				$id	= $ids[0];
				$this->db->where($this->primary_key, $id)->delete($this->table_name);
			}
			foreach($ids as $index => $id){
				if (isset($id) && is_numeric($id)){
				$this->db->where($this->primary_key, $id)->delete($this->table_name);
				}
			}
		}
	}
?>